package com.hm.service.framework.request.post.v2;

import com.alibaba.fastjson2.JSON;
import com.hm.service.framework.request.post.PostHandleBean;
import com.hm.service.framework.request.post.v1.PostControllerHelp_V1;
import com.hm.service.framework.response.ResponseBean;
import com.hm.service.framework.response.ResponseConstant;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Controller基类
 * 只做加解密和封装统一返回体
 */
public abstract class PostControllerBase_V2 {

    private static final Logger logger = LoggerFactory.getLogger(PostControllerBase_V2.class);

    protected String handleRequest(HttpServletRequest req) {
        try {
            String requestUrl = req.getRequestURL().toString();
            String sessionId = req.getHeader("sessionId");
            String body = req.getReader().readLine();
            if (requestUrl.contains("000_000_000")) {
                //session接口请求->给Handle解密处理
                PostHandleBean requestBean = PostControllerHelp_V2.handleSessionRequest(body);
                if (requestBean.isComplete()) {
                    //处理完成给子类实现具体业务
                    return postRequest(requestBean);
                } else {
                    //基类拦截处理后直接返回失败
                    String des = requestBean.getDes();
                    return errorResponse(ResponseConstant.BASE_ERROR_CODE, des, "");
                }
            } else {
                //其他接口请求->给handle处理
                PostHandleBean requestBean = PostControllerHelp_V2.handleNormalRequest(requestUrl, sessionId, body);
                if (requestBean.isComplete()) {
                    //处理完成给子类实现具体业务
                    return postRequest(requestBean);
                } else {
                    //基类拦截处理后直接返回失败
                    String des = requestBean.getDes();
                    return errorResponse(ResponseConstant.BASE_ERROR_CODE, des, "");
                }
            }
        } catch (IOException e) {
            String errorMsg = e.getMessage();
            ResponseBean<String> resultBean = new ResponseBean<>();
            resultBean.setCode(ResponseConstant.BASE_ERROR_CODE);
            resultBean.setDes(errorMsg);
            logger.error(errorMsg);
            return JSON.toJSONString(resultBean);
        }
    }

    protected <T> String successResponse(String realSecretKey, int code, String des, T data) {
        return PostControllerHelp_V1.generateSuccessResponse(realSecretKey, code, des, data);
    }

    protected <T> String errorResponse(int code, String des, T data) {
        return PostControllerHelp_V1.generateErrorResponse(code, des, data);
    }

    //子类具体实现
    protected abstract String postRequest(PostHandleBean reqBean);


}
